package com.buaa.aimall.computeModule.Controller;

import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.computeModule.Convert.ComputeConvert;
import com.buaa.aimall.computeModule.DTO.ComputeDTO;
import com.buaa.aimall.computeModule.DTO.CustomComputeDTO;
import com.buaa.aimall.computeModule.Entity.ComputeEntity;
import com.buaa.aimall.Utils.Exception.BusinessException;
import com.buaa.aimall.computeModule.Service.ComputeService;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.goodsModule.Service.CollectService;
import com.buaa.aimall.userModule.Entity.ShoppingCartEntity;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.userModule.Service.ShoppingCartService;
import com.buaa.aimall.userModule.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.buaa.aimall.computeModule.DTO.FilterComputeDTO;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.userModule.DTO.IdDTO;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/compute/compute")
@CrossOrigin
public class ComputeController {

    @Autowired
    private ComputeService computeService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/create-compute")
    public BaseResponse<Boolean> createCompute(
            @Valid ComputeDTO request,  // 接收计算资源参数
            @RequestPart(value = "docFile", required = false) MultipartFile docFile  // 接收文档文件
    ) {
        ComputeEntity computeEntity = ComputeConvert.INSTANCE.createComputeDTOToEntity(request);
        Boolean result;
        try {
            // 调用服务层并传递文档文件
            computeEntity.setCreator(userService.getCurrentUser().getId());
            computeEntity.setIsCustom(false);
            result = computeService.createCompute(computeEntity, docFile);
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
        return new BaseResponse<>("创建计算资源", result, result);
    }

    @PostMapping("/filter-compute")
    public BaseResponse<PageReturnResult<ComputeEntity>> filterCompute(@Valid @RequestBody FilterComputeDTO filterComputeDTO) {
        UserEntity userEntity = userService.getCurrentUser();
        filterComputeDTO.setFk_creator(userEntity.getId());
        PageReturnResult<ComputeEntity> computeList = computeService.filterCompute(filterComputeDTO);
        return new BaseResponse<>(StatusCode.SUCCESS, "查询成功", computeList);
    }

    @PostMapping("/delete-compute-by-id")
    public BaseResponse<Boolean> deleteComputeById(@Valid @RequestBody IdDTO request) {
        Boolean result = computeService.removeById(request.getId());
        return new BaseResponse<>("根据id删除计算资源成功", "计算资源不存在或已删除", result, result);
    }

    @PostMapping("/update-compute")
    public BaseResponse<Boolean> updateCompute(@Valid @RequestBody ComputeDTO request) {
        ComputeEntity computeEntity = ComputeConvert.INSTANCE.createComputeDTOToEntity(request);
        if (computeEntity.getId() == null) {
            return new BaseResponse<>(StatusCode.PARAM_ERROR, "计算资源ID不能为空", false);
        }
        try {
            boolean result = computeService.updateById(computeEntity);
            if (!result) {
                return new BaseResponse<>(StatusCode.DAO_ERROR, "未找到指定的计算资源", false);
            }
            return new BaseResponse<>(StatusCode.SUCCESS, "修改计算资源成功", true);
        } catch (Exception e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, "修改计算资源失败：" + e.getMessage(), false);
        }
    }

    @PostMapping("/enable-compute")
    public BaseResponse<Boolean> enableCompute(@Valid @RequestBody IdDTO request) {
        try {
            Boolean result = computeService.enableCompute(request.getId());
            return new BaseResponse<>(StatusCode.SUCCESS, "计算资源上架成功", true);
        } catch (BusinessException e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, e.getMessage(), false);
        }
    }

    @PostMapping("/disable-compute")
    public BaseResponse<Boolean> disableCompute(@Valid @RequestBody IdDTO request) {
        try {
            Boolean result = computeService.disableCompute(request.getId());
            return new BaseResponse<>(StatusCode.SUCCESS, "计算资源下架成功", true);
        } catch (BusinessException e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, e.getMessage(), false);
        }
    }

    @PostMapping("/update-compute-doc")
    public BaseResponse<Boolean> updateComputeDoc(
            @RequestParam("id") String id,
            @RequestPart("docFile") MultipartFile docFile
    ) {
        try {
            Boolean result = computeService.updateComputeDoc(id, docFile);
            return new BaseResponse<>(StatusCode.SUCCESS, "文档更新成功", result);
        } catch (BusinessException e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, e.getMessage(), false);
        }
    }

    @PostMapping("/add-custom-compute-to-shopping-cart")
    public BaseResponse<Boolean> addCustomComputeToShoppingCart(@RequestBody CustomComputeDTO dto) {
        var computeEntity = ComputeEntity.builder()
                .name("天数Bi-V150_自定义算力")
                .creator("82a3aeabf1d1d82ed0ce5aa5d4905831") // buaa自定义算力提供方专用用户
                .delFlag(0)
                .type("CPU_GPU")
                .priceByHour(5)
                .priceByDay(100)
                .priceByWeek(300)
                .priceByMonth(1000)
                .isEnable(true)
                .memorySize(dto.getMemory())
                .gpuNumber(dto.getVgpuNum())
                .cpuNumber(dto.getCpuNum())
                .source("buaa")
                .isCustom(true)
                .build();
        computeService.save(computeEntity);
        ShoppingCartEntity shoppingCartEntity = ShoppingCartEntity.builder()
                .computeID(computeEntity.getId())
                .type(dto.getType())
                .quantity(dto.getQuantity())
                .build();
        try {
            shoppingCartService.addToCart(shoppingCartEntity);
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
        return new BaseResponse<>(StatusCode.SUCCESS, "创建自定义算力并添加到购物车成功", true);
    }
} 